// 云函数入口文件
const cloud = require('wx-server-sdk')

//requset包
const request = require('request')

cloud.init()

const db=cloud.database();

async function sendMessageHttp(token,postData) {
  let url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token;
  //新建promise对象，发起http统一下单请求
  return new Promise((resolve, reject) => {
    try {
      request.post({
        url: url,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/json",
        },
        body: postData
      },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            return resolve(body)
          } else {
            return reject(error)
          }
        })
    } catch (e) {
      return reject(e)
    }
  })
}
// 云函数入口函数
exports.main = async (event, context) => {

let tokenPromise=await cloud.callFunction({
    name:'getToken'
})
  if (tokenPromise.errMsg =='callFunction:ok')
  {
    let token = tokenPromise.result;
    if (token!='') //获取token正确
    {
      // return{
      //   token: token,
      //   data: event.postData
      // }
      return await sendMessageHttp(token, event.postData)
    }
    else
    {
      return {
        result: 'fail',
        error: '错误：getToken云函数返回token为空'
      }
    }

  }
  else
  {
    return {
      result:'fail',
      error:'错误：调用getToken云函数失败'
    }
  }

}